package com.cgy.utils.elasticsearch.search;

import com.cgy.utils.elasticsearch.condition.Condition;
import com.cgy.utils.elasticsearch.ql.ElasticQLHelper;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;

import java.util.Objects;

/**
 * @author CH
 */
public class ElasticSearchHelper {
	
	private static SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    /**
     * 查询
     * @param condition
     * @return
     */
    public static SearchRequest search(Condition condition) {
        QueryBuilder query = ElasticQLHelper.generateQueryByFields(condition);
        FieldSortBuilder order = ElasticQLHelper.generateFieldSort(condition);

        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(condition.getTimeout()));
        if(null != query) {
        	searchSourceBuilder.query(query);
        }
        if(null != order) {
        	searchSourceBuilder.sort(order);
        }
        searchSourceBuilder.from(condition.getStart() - 1);

        int size = condition.getSize();
        if(Objects.nonNull(size)) {
            if(size > 10000) {
                size = 10000;
            }
            searchSourceBuilder.size(size);
        }

        SearchRequest searchRequest = new SearchRequest(condition.getIndex());
        searchRequest.source(searchSourceBuilder);

        return searchRequest;
    }

    /**
     *
     * @param condition
     * @return
     */
    public static SearchRequest scroll(Condition condition) {
        SearchRequest request = search(condition);
        final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(condition.getScrollTime()));
        request.scroll(scroll);

        return request;
    }
}
